<?php                    
/**
 * 数据库操作类
 * @author: yubing
 */                            
class db extends PDO {
    public $table;   //当前操作的数据表名字
    protected $fields;
    private $where = array();
    public $sql;
    public $msg;                 
    /**
     * 初始化一个数据库实例
     * 
     * @param string $configKey  数据库配置项
     * @param int $index //索引值,根据这个值获取计算数据源 'db'=>[0,1,2]
     * @return db
     */
    public function __construct($configKey = 'db', $index =0) {
        $config = config::$$configKey; // config::db       
        $dsn = $config['dsn'][$index]; // $index在第几台服务器 
        parent::__construct($dsn,$config['user'],$config['pass'],$config['options']);
    }

    /**
     * 插入数据
     * 
     * @param array $data   
     */
    public function insert($data = array()) {
        $this->sql = sprintf('insert into %s set %s', $this->table, implode(',', $this->joinKeyVal($data)));
        if(!$this->query($this->sql)) {
            $this->msg = $this->errorInfo(); 
            return false;
        }
        return $this->lastInsertId();
    }
    /**
     * 计算有多少条记录
     * 
     */
    public function count() {
        $this->sql = sprintf('select count(*) from %s %s', $this->table, $this->condition());
        $sth = $this->query($this->sql);
        $res = $sth->fetchColumn(0);       
        return (int)$res;
    }

    public function row($sql,$type=PDO::FETCH_ASSOC){
        $sth = $this->query($sql);
        if (!$sth) { 
            $this->msg = $this->errorInfo();
            return array();
        }
        return $sth->fetch($type);
    }
    public function rows($sql,$start=0,$size=0,$type=PDO::FETCH_ASSOC) {
        $sql = $size > 0 ? sprintf('%s limit %d,%d',$sql ,$start,$size) : $sql;
        $sth = $this->query($sql);
        if (!$sth) {
            $this->msg = $this->errorInfo();
            return array();
        }
        return $sth->fetchAll($type);
    }
    /**
     * 更新数据
     * 
     * @param array $data    
     */
    public function update($data = array()) {  
        $this->sql = sprintf('update %s set %s %s' , $this->table, implode(',' , $this->joinKeyVal($data)) , $this->condition());
        $ret = $this->exec($this->sql);
        return $ret!==false;
    }
   /**
   * 根据查询条件返回一条记录
   */
	public function find(){
		$sql = 'select * from '.$this->table . $this->condition();
		return $this->row($sql);
	}
    /**
     * 删除数据
     * 
     */
    public function delete() {
        $this->sql = 'delete from '.$this->table. $this->condition();
        $ret = $this->exec($this->sql);
        if($ret===false){
            $this->msg = $this->errorInfo();
        }
        return $ret!==false;
    }
    /**
     * 设置各种查询条件
     * 
     * @param mixed $input
     */
    public function where($input) {
        if (is_string($input)) {
            $this->where[] = $input;
        } else if (is_array($input)){
			array_merge($this->where, $this->joinKeyVal($input));
        }
        return $this;                  
    }

        
    public function condition(){ 
        return count($this->where) ? ' where '.implode(' and ',$this->where) : '';
    }
   /**
   * 设置数据表名称，值
   *  
   * @param bool $name
   * @param mixed $fields
   */
    public function table($name,$fields=array()){    
        $this->table = $name;
        $this->fields = $fields;
		return $this;
    }
    public function reset() {
        $this->sql = '';   
        $this->where = array();
		return $this;
    }
	/**
	 *@param array $data
	 * 拼接key valure 数组为 = 连接的数据
	 * */
	public function joinKeyVal($data){
		$arr = array();
		foreach($data as $k=>$v){
			if(count($this->fields) && !in_array($k,$this->fields)){
				continue;
			}
			array_push($arr,sprintf("%s=%s",$k,self::q($v)));
		}
		return $arr;
	}
    /**
	*　给字符串,添加'
	*/
	public static function q($v){
		return "'".  str_replace(array("\\","'"),array('',"\\'"),trim($v,"'")) . "'";
	}
}
/*
include_once 'config.php';
$db = new db('db');
//$db->query('set names utf8') ;
$sql  = 'select * from user';
$rows = $db->rows($sql,0,20);
echo '<pre>';
print_r($rows);
*/